<template>
  <div class="upload-resume-container">
    <!-- 标题 -->
    <div class="title-section">
      <h2>选择一份简历</h2>
    </div>

    <!-- 上传区域 -->
    <el-upload
      ref="uploadRef"
      class="upload-area"
      drag
      action="#"
      :auto-upload="false"
      :show-file-list="false"
      :on-change="handleFileChange"
      :accept="'.pdf,.docx'"
      :disabled="loading"
    >
      <div class="upload-icon">
        <svg width="48" height="48" viewBox="0 0 48 48" fill="none" xmlns="http://www.w3.org/2000/svg">
          <path d="M24 6V18M24 18L18 12M24 18L30 12M24 30H24.01M24 30C27.3137 30 30 27.3137 30 24C30 20.6863 27.3137 18 24 18C20.6863 18 18 20.6863 18 24C18 27.3137 20.6863 30 24 30Z" stroke="#9c27b0" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
          <path d="M24 30V42M24 42H24.01" stroke="#9c27b0" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
        </svg>
      </div>
      <p class="upload-text">点击上传简历文件或将文件拖拽至此处</p>
      <p class="file-info">支持pdf、docx格式文件，大小不超过7M</p>
    </el-upload>

    <!-- 按钮区域 -->
    <div class="button-group">
      <el-button type="primary" size="large" @click="handleLocalUpload" :disabled="loading">
        本地上传
      </el-button>
      <!-- <el-button size="large" @click="handleFromMyResume" :disabled="loading">
        从我的简历选择
      </el-button> -->
    </div>
    
    <!-- 添加加载状态 -->
    <div v-if="loading" class="loading-overlay">
      <div class="loading-content">
        <div class="loading-spinner"></div>
        <p v-if="!taskStatus">正在上传并分析简历，请稍候...</p>
        <div v-else-if="taskStatus === 'processing'">
           <h3 class="loading-title"> 请耐心等待，预计用时1分钟</h3>  
         
           <p>分析处理中... 已用时间: {{ processingTime }}秒</p>  

        </div>
        <p v-else-if="taskStatus === 'failed'">处理失败</p>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref ,onBeforeUnmount} from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { PredictApi } from '@/utils/api.js'

const router = useRouter()

// 获取 el-upload 组件实例
const uploadRef = ref()
const loading = ref(false)
const taskStatus = ref(null)
const processingTime = ref(0)
const taskId = ref(null)
const pollInterval = ref(null)
const uploadedFileName = ref('') // 存储上传的文件名

// 处理文件变化
const handleFileChange = async (file) => {
  if (!isValidFile(file.raw)) {
    ElMessage.error('不支持的文件类型或文件过大，请选择 pdf、docx 格式且大小不超过 7M 的文件')
    // 清除已选择的文件
    uploadRef.value?.clearFiles()
    return
  }
  
  // 保存文件名
  uploadedFileName.value = file.raw.name
  
  // 上传文件进行预测
  await uploadFile(file.raw)
}

// 验证文件是否合法（只允许PDF和DOCX格式）
const isValidFile = (file) => {
  const validTypes = ['application/pdf', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document']
  const maxSize = 7 * 1024 * 1024 // 7MB
  return validTypes.includes(file.type) && file.size <= maxSize
}

// 上传文件逻辑
const uploadFile = async (file) => {
  try {
    loading.value = true
    taskStatus.value = null // 重置任务状态
    processingTime.value = 0 // 重置处理时间
    
    // 使用 FormData 上传文件
    const formData = new FormData()
    formData.append('resume', file)
    
    // 调用异步预测 API
    const response = await PredictApi.predictFromResumeAsync(formData, true)
    
    // 获取任务ID
    taskId.value = response.data.task_id
    
    // 开始轮询任务状态
    pollTaskStatus(taskId.value)
    
    ElMessage.success('文件上传成功，正在分析中...')
    console.log('任务已提交:', response)
    
  } catch (error) {
    console.error('上传失败:', error)
    ElMessage.error('上传失败: ' + (error.message || '未知错误'))
    loading.value = false
    // 清除已选择的文件
    uploadRef.value?.clearFiles()
  }
}

// 轮询任务状态
const pollTaskStatus = (taskId) => {
  pollInterval.value = setInterval(async () => {
    try {
      const response = await PredictApi.getPredictStatus(taskId)
      const data = response
      
      taskStatus.value = data.data.status
      processingTime.value = data.data.elapsed_time
      
      if (data.data.status === 'completed') {
        clearInterval(pollInterval.value)
        loading.value = false
        
        // 将结果数据保存到localStorage
        const resultData = {
          ...data.data.result,
          form_data: { resume: uploadedFileName.value }
        };
        localStorage.setItem('predictResult', JSON.stringify(resultData));
        
        router.push({
              path: '/predict-result'
        });
        
      } else if (data.data.status === 'failed') {
        clearInterval(pollInterval.value)
        loading.value = false
        ElMessage.error('任务处理失败: ' + data.data.error)
        // 清除已选择的文件
        uploadRef.value?.clearFiles()
      }
    } catch (error) {
      clearInterval(pollInterval.value)
      loading.value = false
      ElMessage.error('轮询任务状态失败：' + error.message)
      // 清除已选择的文件
      uploadRef.value?.clearFiles()
    }
  }, 2000); // 每2秒轮询一次
}

// 本地上传按钮点击
const handleLocalUpload = () => {
  // 触发 el-upload 的点击事件
  uploadRef.value?.$el.querySelector('input')?.click()
}

// 从我的简历选择
// const handleFromMyResume = () => {
//   alert('从我的简历选择功能暂未实现')
//   // 可跳转到简历列表页
// }

// 组件销毁前清除轮询
onBeforeUnmount(() => {
  if (pollInterval.value) {
    clearInterval(pollInterval.value)
  }
})
</script>

<style scoped>
.loading-title{
  color: chocolate;
}


.upload-resume-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  /* justify-content: center; */
  min-height: 74vh;
  max-width: 1200px;
  margin: auto;
  /* background-color: #f5f7fa; */
  padding: 40px;
  font-family: 'Microsoft YaHei', sans-serif;
  position: relative;
}

.title-section {
  margin-bottom: 30px;
  text-align: center;
}

.title-section h2 {
  font-size: 24px;
  color: #333;
  margin: 0;
}

.upload-area {
  width: 100%;
  max-width: 500px;
}

.upload-area :deep(.el-upload) {
  width: 100%;
}

.upload-area :deep(.el-upload-dragger) {
  width: 100%;
  height: 200px;
  border: 2px dashed #9c27b0;
  border-radius: 12px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  background-color: #ffffff;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.upload-area :deep(.el-upload-dragger:hover) {
  border-color: #7b1fa2;
  background-color: #f8f9fa;
}

.upload-area :deep(.el-upload-dragger.is-dragover) {
  border-color: #7b1fa2;
  background-color: #f8f9fa;
}

.upload-area :deep(.el-upload-dragger.is-disabled) {
  cursor: not-allowed;
  opacity: 0.6;
}

.upload-area :deep(.el-upload-dragger.is-disabled:hover) {
  border-color: #9c27b0;
  background-color: #ffffff;
}

.upload-icon {
  margin-bottom: 16px;
  color: #9c27b0;
}

.upload-text {
  font-size: 16px;
  color: #333;
  text-align: center;
  margin-bottom: 8px;
}

.file-info {
  font-size: 14px;
  color: #666;
  text-align: center;
}

.button-group {
  display: flex;
  gap: 20px;
  margin-top: 30px;
  width: 100%;
  max-width: 500px;
  justify-content: center;
}

.el-button {
  padding: 12px 24px;
  border-radius: 8px;
  font-size: 16px;
  transition: all 0.3s ease;
}

.el-button.primary {
  background: linear-gradient(135deg, #9c27b0, #7b1fa2);
  color: white;
  border: none;
}

.el-button.primary:hover {
  background: linear-gradient(135deg, #7b1fa2, #5e1a8d);
}

.el-button.default {
  background: #ffffff;
  color: #9c27b0;
  border: 1px solid #9c27b0;
}

.el-button.default:hover {
  background: #f5f5f5;
}

.el-button:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(255, 255, 255, 0.9);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
  border-radius: 12px;
}

.loading-content {
  text-align: center;
  background: white;
  padding: 30px;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}

.loading-spinner {
  display: inline-block;
  width: 40px;
  height: 40px;
  border: 3px solid #e5e5e5;
  border-top-color: #9c27b0;
  border-radius: 50%;
  animation: rotate 1s linear infinite;
  margin-bottom: 10px;
}

@keyframes rotate {
  to {
    transform: rotate(360deg);
  }
}

.loading-content p {
  margin-top: 10px;
  color: #9c27b0;
  font-size: 16px;
  font-weight: 500;
}
</style>